var eventObj = require("../event");
var udpOperation = require("../../net/udpOperation")
var fs = require("fs");
var _ = require("underscore");
var TramStatus = require("../basic/TramStatus");
var IndicatorStatus = require("../basic/IndicatorStatus");
var RouteStatus = require("../basic/RouteStatus");
var SegmentStatus = require("../basic/SegmentStatus");
var TerminusStatus = require("../basic/TerminusStatus");
var TurnoutStatus = require("../basic/TurnoutStatus");
var baseInfoUtil = require("../baseInfo");
var jsonfile = require("jsonfile");

function RunExecutor(){
	 this.line = null;
	 this.segmentStatusArr = [];
	 this.terminusStatusArr = [];
	 this.routeStatusArr = [];
	 this.operationPathStatusArr = [];
     this.indicatorStatusArr = [];
     this.turnoutStatusArr = [];
     this.tramStatusArr = [];
     this.interval = null;
     this.updateInterval = 2;
    //模拟车辆数量
     this.tramNum = 0;
     this.runFlag = false;
    //GPS数据测试用 待删除
     this.gpsDataArr = [];
     this.gpsIndex = 0;
}

var runExecutor = new RunExecutor();

module.exports = runExecutor;

//监听网络配置参数文件修改
eventObj.event.on("app_event_netArgs_update", function (data) {
    jsonfile.writeFile('./config/properties.json', data, function (err) {
        if(err){
            console.error(err)
        }
    })

})

/*获取车辆运行计划事件*/
eventObj.event.on("app_event_tram_simulate",function(data){

     var runPlan = baseInfoUtil.createTramRunPlan(data);
     runExecutor.tramNum += runPlan.length;
     _.each(runPlan,function(element,index){
         var tramCode = index >= 9 ? '10' + (index+1) : '100' + (index+1);
         var serviceNum = null;
        if(index<10){
          //构造车辆运行服务号
          serviceNum = Number("100" + index+"00");
          }else{
          serviceNum =  Number("100" + index+"0");
        }
         var tram = new TramStatus({
                                  serviceNum    :  serviceNum,
                                  runExecutor   :  runExecutor,
                                  initTimeBySec :  baseInfoUtil.getSysTimeBySecs(),
                                  tramCode      :  tramCode,
                                  runPlan       :  element
                                //  crossStationArr : obj.crossStationArr
                             });
         tram.init();
         runExecutor.tramStatusArr.push(tram);

  });
  runExecutor.run();   

});

/*获取添加车辆事件*/
eventObj.event.on("app_event_tram_add",function(data){
   var tempPathArr = data.path.split("-");
   var startTerminusCode = data.startTerminus;
   var startSegmentCode = runExecutor.getTerminusByCode(startTerminusCode).segmentCode;
   var pathArr = _.rest(tempPathArr,_.indexOf(tempPathArr,startTerminusCode));
   var runPlan ={
                 avgSpeed   : data.avgSpeed,
                 avgStopTime: data.avgStopTime,
                 returnTime : data.reentryTime,
                 startTime  : baseInfoUtil.getSysTimeBySecs(),
                 path       : pathArr.join('-'),
                 runTimes   : data.runTimes
                 };
   runExecutor.tramNum++;
   var tramCode = runExecutor.tramNum >= 10 ? '10' + runExecutor.tramNum : '100' + runExecutor.tramNum; 
   var serviceNum = runExecutor.tramNum >= 10 ? Number("100" + runExecutor.tramNum+"0") : Number("100" + runExecutor.tramNum+"00");
   var tram = new TramStatus({
                          serviceNum    :  serviceNum,
                          runExecutor   :  runExecutor,
                          initTimeBySec :  baseInfoUtil.getSysTimeBySecs(),
                          tramCode      :  tramCode,
                          runPlan       :  runPlan,
                          startSegmentCode : startSegmentCode,
                          //此处逻辑要算出totalDistance真正长度
                          totalLength  :  100,
                          tramStyle  : "addTram"
                        //  crossStationArr : obj.crossStationArr
                     });
   tram.init();
   runExecutor.tramStatusArr.push(tram);
   if(!runExecutor.runFlag){
    runExecutor.run();
   }

 })



/*处理基础数据*/
RunExecutor.prototype.init = function(){
   var $this = this;	
   udpOperation.createUdpServer();
   // var basicData = eval("(" + fs.readFileSync("./datas/BasicData.json", "utf-8")+ ")");
   // $this.gpsDataArr = eval("(" + fs.readFileSync("./datas/longi_latitude_data.json", "utf-8")+ ")");

   // $this.line = basicData.Line[0];

   // $this.operationPathStatusArr = basicData.OperationPath;

   // _.forEach(basicData.Segment,function(ele){
   //    var segmentStatus = new SegmentStatus();
   //    segmentStatus.runExecutor = $this;
   //    _.extend(segmentStatus,ele);
   //    $this.segmentStatusArr.push(segmentStatus);
   // })

   // _.forEach(basicData.Terminus,function(ele){
   //    var terminusStatus = new TerminusStatus();
   //    _.extend(terminusStatus,ele);
   //    $this.terminusStatusArr.push(terminusStatus);
   // })

   // _.forEach(basicData.BaseDevice,function(ele,index){
   //     if("indicator" === ele.type){
   //       $this.indicatorStatusArr.push(new IndicatorStatus(ele))
   //     }
   //     if("turnout" === ele.type){
   //       $this.turnoutStatusArr.push(new TurnoutStatus(ele))
   //     }
   // })
   // _.forEach(basicData.Route,function(ele){
   //    var routeStatus = new RouteStatus(ele);
   //    routeStatus.runExecutor = $this;
   //    $this.routeStatusArr.push(routeStatus);
   // })
   // _.forEach($this.routeStatusArr,function(ele){
   //    ele.next = $this.getRouteById(ele.nextRouteId);
   // })

   // _.forEach($this.segmentStatusArr,function(ele,index){
   //    ele.previous = $this.getSegmentById(ele.previousId);
   //    ele.next = $this.getSegmentById(ele.nextId);
   //    if(ele.isSwitch){
   //       ele.rnext = $this.getSegmentById(ele.rnextId);
   //    }
   // })
   // _.forEach($this.terminusStatusArr,function(ele,index){
   //    ele.segment = $this.getSegmentById(ele.segmentId);
   // })
}

RunExecutor.prototype.run = function(){
   var $this = this;
   $this.runFlag = true;
   if($this.interval){
      clearInterval($this.interval);
   }
   var update = function(){
      var tramEvents = [];
      var deviceEvents = [];
      _.forEach($this.tramStatusArr,function(ele,index){
            ele.run();
            if(ele.isOnline()){
               tramEvents.push(ele.sendStatusEventInfo());
                //通过车辆状态驱动路由状态变化，主要是显示道岔效果
                // _.forEach($this.routeStatusArr,function(e){
                //     e.reactToTram(ele);
                // })
                // _.forEach($this.terminusStatusArr,function(e){
                //     e.reactToTram(ele);
                //     var deviceStatusEventInfo = {
                //         "type" : "terminus",
                //         "code" : e.code,
                //         "status" : e.status
                //     }
                //     deviceEvents.push(deviceStatusEventInfo);
                // })
                // _.forEach($this.segmentStatusArr,function(e){
                //     e.reactToTram(ele);
                //     var deviceStatusEventInfo = {
                //         "type" : "segment",
                //         "code" :  e.code,
                //         "status" : e.status,
                //         "opStatus" :e.opStatus
                //     }
                //     deviceEvents.push(deviceStatusEventInfo);
                // })
            };

      })
      //  _.forEach($this.turnoutStatusArr,function(ele){
      //      var deviceStatusEventInfo = {
      //          "type" : "turnout",
      //          "code" :  ele.code,
      //          "status" : ele.status,
      //          "opStatus" :ele.opStatus
      //      }
      //      // console.log(deviceStatusEventInfo)
      //      deviceEvents.push(deviceStatusEventInfo);
      //  })
      // _.forEach($this.indicatorStatusArr,function(ele){
      //    var deviceStatusEventInfo = {
      //       "type" : "indicator",
      //       "code" :  ele.code,
      //       "status" : ele.status,
      //       "opStatus" :ele.opStatus 
      //    }
      //    deviceEvents.push(deviceStatusEventInfo);
      // })
       /**
        * GPS测试逻辑 待删除
        *
        */
      /* var obj = $this.gpsDataArr[$this.gpsIndex];
       var gpsInfo = {
           "tramCode":"1001",
           "packetNum":111,
           "longitudeInt": obj.longitude[0],
           "longitudeDee": obj.longitude[1],
           "latitudeInt": obj.latitude[0],
           "latitudeDee": obj.latitude[1]
       }
       if($this.gpsIndex === $this.gpsDataArr.length - 1){
           $this.gpsIndex = 0;
       }else{
           $this.gpsIndex ++;
       }
       eventObj.event.emit("tram_gps_change_event",gpsInfo);*/
       
      // eventObj.event.emit("device_status_change_event",deviceEvents);
      eventObj.event.emit("tram_status_change_event",tramEvents);

   }
   $this.interval = setInterval(update,$this.updateInterval*1000);
}

RunExecutor.prototype.getSegmentById = function(id){
   var $this = this;
   var obj = null;
   _.forEach($this.segmentStatusArr,function(ele,index){
      if(ele.id === id){
         obj = ele
      }
   })
   return obj;
}
RunExecutor.prototype.getRouteById = function(id){
   var $this = this;
   var obj = null;
   _.forEach($this.routeStatusArr,function(ele){
      if (ele.id === id) {
        obj = ele;
      };
   })
   return obj;
}
RunExecutor.prototype.getTramStatusByCode = function(code){
   var $this = this;
   var obj = null;
   _.forEach($this.tramStatusArr,function(ele,index){
      if(ele.code === code){
         obj = ele;
      }
   })
   return obj;
}
RunExecutor.prototype.getTerminusByCode = function(code){
   var $this = this;
   var obj = null;
   _.forEach($this.terminusStatusArr,function(ele,index){
      if(ele.code === code){
         obj = ele;
      }
   })
   return obj;
}
RunExecutor.prototype.getTurnoutStatusByCode = function(code){
   var $this = this;
   var obj = null;
   _.forEach($this.turnoutStatusArr,function(ele,index){
      if(ele.code === code){
         obj = ele;
      }
   })
   return obj;
}
RunExecutor.prototype.getIndicatorStatusByCode = function(code){
   var $this = this;
   var obj = null;
   _.forEach($this.indicatorStatusArr,function(ele,index){

      if(ele.code === code){
         obj = ele;
      }
   })
   return obj;
}
RunExecutor.prototype.getSegmentStatusByCode = function(code){
   var $this = this;
   var obj = null;
   _.forEach($this.segmentStatusArr,function(ele,index){
      if(ele.code === code){
         obj = ele;
      }
   })
   return obj;
}
/*获取线路的总长度*/
RunExecutor.prototype.getLineTotalLength = function(){
   var $this = this;
   var totalLength = 0;
   _.forEach($this.segmentStatusArr,function(ele,index){
       totalLength += ele.Length;
   })
   return totalLength;
}
/*获取当前的路径*/
RunExecutor.prototype.getCurrentRouteByDirect = function(direct){
   var $this = this;
   var obj = null;
   _.forEach($this.routeStatusArr,function(ele){
      if(ele.direct === direct){
        obj = ele;
      }
   })
   return obj;

}